﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using UIShare;
using EFong.View.Proxy;
using EFong.Contract;

namespace EFong.View.Financing
{
    public partial class Frm_TrainCustomerSettlement : BasicMdiChildForm
    {
        private Proxy.FinanceServiceProxy _financeServiceProxy { get { return Proxy.FinanceServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }
        private Proxy.BaseServiceProxy _baseServiceProxy { get { return Proxy.BaseServiceProxy.GetInstance(); } }

        private List<RCustomer> customerList = null;

        private List<火车票支付单> orderList = null;
        //private List<火车票支付单> usedOrderList = null;

        private Contract.Customer _customer;
        public Contract.Customer Customer
        {
            get { return _customer; }
            set
            {
                _customer = value;
                onCustomerChanged();
            }
        }

        public Frm_TrainCustomerSettlement()
        {
            InitializeComponent();
            cmb_BankAccount.ReadOnly(true);
        }

        protected override void InitFields()
        {
        }

        protected override void LoadDatas()
        {
            orderList = _financeServiceProxy.GetTicketOrder().ReturnValue;
            grd_Orders.DataSource = orderList;
            //this.cmb_Customer.Properties.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            customerList = _masterProxy.GetAllCustomer().ReturnValue;
            bds_Customer.BindingData(customerList);
            this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllBankAccount().ReturnValue);
            this.dte_PostingDate.DateTime = DateTime.Now;
            this.dte_SettlementDate.DateTime = DateTime.Now;

        }

        protected override void Events()
        {
            this.cmb_Customer.EditValueChanged += (s, e) =>
            {
                loadCustomer();
            };

            //this.gv_Orders.CellValueChanged += (s, e) =>
            //{
            //    refreshSelect();
            //};

            this.cmb_PayType.SelectedIndexChanged += (s, e) =>
            {
                if (ViewState == ViewStates.EDIT) { return; }

                this.cmb_BankAccount.SetValue(default(Contract.BankAccount));
                this.cmb_BankAccount.ReadOnly(this.cmb_PayType.SelectedIndex <= 0);
            };

            this.cmb_BankAccount.SelectedIndexChanged += (s, e) =>
            {
                Contract.BankAccount bankAccount = cmb_BankAccount.GetValue() as Contract.BankAccount;
                if (bankAccount == null)
                    txt_BankAccountAmount.Text = "0";
                else
                    txt_BankAccountAmount.Text = string.Format("{0} {1}", bankAccount.Currency.Code, bankAccount.Amount);
            };
            this.gv_Orders.CellValueChanging += (s, e) =>
            {
                if (e.Column != colSelect)
                    return;

                火车票支付单 order = gv_Orders.GetRow(e.RowHandle) as 火车票支付单;
                if (order == null)
                    return;
                this.gv_Orders.BeginDataUpdate();
                selectOrders(order, !order.IsSelect);
                this.gv_Orders.EndDataUpdate();

                if (order.IsSelect)
                {
                    RCustomer customer = customerList.FirstOrDefault(v => v.Name == order.Customer);
                    this.cmb_Customer.SetValue(customer);
                    this._customer = _masterProxy.GetCustomerByID(customer.ID).ReturnValue;
                }

                refreshSelect();
            };
        }

        private void selectOrders(火车票支付单 order, bool isSelect)
        {
            orderList.ForEach(o =>
            {
                if (o.ID == order.ID)
                {
                    o.IsSelect = isSelect;
                }
                else
                {
                    if (isSelect)
                    {
                        if (o.Customer != order.Customer)
                            o.IsSelect = false;
                    }
                }
            });
        }

        private void refreshSelect()
        {
            decimal totalReceive = 0;
            decimal totalIntergral = 0;
            foreach (火车票支付单 order in (grd_Orders.DataSource as List<火车票支付单>))
            {
                if (order.IsSelect)
                {
                    totalIntergral += order.Intergral;
                    totalReceive += order.Money;
                }
            }

            this.txt_TotalAccountReceivable.Text = totalReceive.ToString();
            this.txt_TotalIntergral.Text = totalIntergral.ToString();

            grd_Orders.RefreshDataSource();
            this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllBankAccount().ReturnValue);
        }

        void loadCustomer()
        {
            RCustomer rCustomer = this.cmb_Customer.GetValue() as RCustomer;
            if (rCustomer == null)
                return;
            Customer = _masterProxy.GetCustomerByID(rCustomer.ID).ReturnValue;
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void save()
        {
            if (Customer == null)
            {
                MsgBox.Error("请先选择客户");
                return;
            }

            CustomerSettlement customerSettlement = new CustomerSettlement();
            customerSettlement.Amount = txt_Amount.GetValue();
            customerSettlement.BankAccount = cmb_BankAccount.GetValue() as Contract.BankAccount;
            customerSettlement.CheckNo = txt_CheckNo.GetText();
            customerSettlement.Customer = Customer;
            customerSettlement.Intergral = txt_UseIntergral.GetValue();
            customerSettlement.OrderList = getOrderList();
            customerSettlement.PaymentType = cmb_PayType.GetValue() as string;
            customerSettlement.PostingDate = dte_PostingDate.GetValue(DateTime.MinValue);
            customerSettlement.Remark = txt_Remark.GetText();
            customerSettlement.SettlementDate = dte_SettlementDate.GetValue(DateTime.MinValue);

            if (_financeServiceProxy.CustomerSettle(customerSettlement).IsSuccess)
            {
                MsgBox.Info("保存成功");
                resetData();
                this.cmb_Customer.SetValue(null);
                this.txt_Amount.SetValue(0);
                this.txt_BankAccountAmount.SetText(string.Empty);
                //loadCustomer();
                //refreshSelect();
            }
        }

        private void resetData()
        {
            orderList = _financeServiceProxy.GetTicketOrder().ReturnValue;
            grd_Orders.DataSource = orderList;
        }

        private List<Order> getOrderList()
        {
            List<Guid> temp = new List<Guid>();
            List<Order> resultList = new List<Order>();

            List<火车票支付单> usedOrderList = (from o in orderList
                                          where o.Customer == Customer.Name && o.IsSelect
                                          select o).ToList();

            foreach (支付单 支付单 in usedOrderList)
            {
                if (!支付单.IsSelect)
                    continue;

                if (temp.Contains(支付单.ID))
                    continue;

                Order order = new Order()
                {
                    ID = 支付单.ID,
                    Ref = 支付单.Ref,
                    OrderType = 支付单.Type,
                    Money = (from z in orderList
                             where z.ID == 支付单.ID
                             select z.Money).Sum(),
                    MoneyCurrency = 支付单.Currency,
                    Intergral = 支付单.Intergral
                };

                temp.Add(order.ID);
                resultList.Add(order);
            }

            return resultList;

        }


        void onCustomerChanged()
        {
            if (Customer == null)
            {
                // clear customer datas
                this.txt_CustomerIntergral.Text = string.Empty;

                //List<飞机票支付单>  list = new List<飞机票支付单>();
                //this.grd_Orders.DataSource = orderList;
                orderList.ForEach(o => o.IsSelect = false);
                this.grd_Orders.DataSource = orderList;
                this.cmb_Customer.SetText(string.Empty);

                //this.txt_CustomerIntergral.Text = string.Empty;

                //this.usedOrderList = new List<火车票支付单>();
                //this.grd_Orders.DataSource = orderList;
            }
            else
            {
                this.txt_CustomerIntergral.Text = Customer.Intergral.ToString();
                this.txt_PrePay.Text = Customer.Amount.ToString();

                orderList.ForEach(o => o.IsSelect = false);

                List<火车票支付单> usedOrderList = (from o in orderList
                                              where o.Customer == Customer.Name
                                              select o).ToList();
                usedOrderList.ForEach(o => o.IsSelect = true);
                this.grd_Orders.DataSource = usedOrderList;

                //this.txt_CustomerIntergral.Text = Customer.Intergral.ToString();
                //this.txt_PrePay.Text = Customer.Amount.ToString();

                //this.usedOrderList = (from o in orderList
                //                      where o.Customer == Customer.Name
                //                      select o).ToList();
                //this.grd_Orders.DataSource = usedOrderList;
            }

            refreshSelect();
        }

        private void btn_AllCustomer_Click(object sender, EventArgs e)
        {
            this.Customer = null;
        }
    }
}
